package softtech.apps.dangtinraovat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.google.android.gms.gcm.GoogleCloudMessaging;

import softtech.apps.adapter.ProductAdapter;
import softtech.apps.adapter.ProductEndlessAdapter;
import softtech.apps.adapter.UserListAdapter;
import softtech.apps.model.Product;
import softtech.apps.utilities.HttpRequest;
import softtech.apps.utilities.SessionManager;
import softtech.apps.utilities.Utilities;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ActivityMain extends Activity{
	ShareExternalServer appUtil;
	String regId;
	AsyncTask<Void, Void, String> shareRegidTask;
	GoogleCloudMessaging gcm;
	Context context;
	static final String TAG = "Main Activity";
	UserListAdapter userAdapter;
	//IntefaceProductListView lvProducts;
	ListView lvProducts;
	//ProductEndlessAdapter adapter;
	ProductAdapter adapter;
	private ProgressDialog pdia;
	int mult = 1;
	private final static int ITEM_PER_REQUEST = 30;
	
	SessionManager session;
	Button btnLogout;
	TextView tvUserInfo;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		context = getApplicationContext();
		
		session = new SessionManager(context);
		 btnLogout = (Button) findViewById(R.id.btLogout);
		 tvUserInfo = (TextView) findViewById(R.id.tvUserInfo);
		// Get REG ID here and store in current device
        appUtil = new ShareExternalServer();
        SharedPreferences sp = getPreferences(MODE_PRIVATE);
        regId = sp.getString(Utilities.REG_ID, "");
        
        // Get regId has stored before
        if (TextUtils.isEmpty(regId)) {
			regId = registerGCM(); // Nho kiem tra truong hop co internet hay khong
			Log.d("ActivityMain", "GCM RegId: " + regId);
		}        
        
        // Kiem tra login, get chi tiet user o day bao gom UserId tu phia server tra ve
        // So dien thoai = user de dang nhap
        session.checkLogin();
        HashMap<String, String> user = session.getUserDetails();
        String phone_number = user.get(SessionManager.KEY_PHONE_NUMBER);
        String user_id = user.get(SessionManager.KEY_USER_ID);
        String hello = "Hello: "+phone_number+" "+user_id;
        tvUserInfo.setText(hello);
        btnLogout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// Clear the session data
				// This will clear all session data and 
				// redirect user to LoginActivity
				session.logoutUser();
			}
		});
        
        if(!TextUtils.isEmpty(regId)){
        	//AsyncUsers task = new AsyncUsers();
        	AsyncProducts task = new AsyncProducts();
        	task.execute();
        }
        
	}
	
	private class AsyncProducts extends AsyncTask<String, Void, List<Product>> {
		
		@Override
		protected void onPreExecute(){ 
		   super.onPreExecute();
		        pdia = new ProgressDialog(ActivityMain.this);
		        pdia.setMessage("Loading...");
		        pdia.show();    
		}

		@Override
	    protected void onPostExecute(List<Product> result) {            
	        super.onPostExecute(result);
	        pdia.dismiss(); 
	        lvProducts = (ListView) findViewById(R.id.lvProducts);
	        adapter = new ProductAdapter(context, result);
	        lvProducts.setAdapter(adapter);
	        lvProducts.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
		        	//Toast.makeText(getApplicationContext(),"Already Registered with GCM Server!",Toast.LENGTH_LONG).show();
					Intent intent = new Intent(ActivityMain.this,ActivityProductDetail.class);
			        Log.d("ActivityMain", "GCM RegId: " + regId);
			        int user_id = adapter.getItem(position).getpUserId();
			        Log.d(TAG, "User Id clicked = "+user_id);
			        int pServerId = adapter.getItem(position).getpServerId();
					intent.putExtra("user_id",user_id);
					intent.putExtra("pServerId",pServerId);
					
//					Log.d(TAG, "Gia tri cua user id = "+String.valueOf(user_id));
//					Log.d(TAG, "Gia tri cua product id = "+String.valueOf(pServerId));
				    startActivity(intent);
				    //finish();
					Log.d(TAG, "Click de xem chi tiet san pham");
				}
			});
	    }

		@Override
		protected List<Product> doInBackground(String... params) {
			// TODO Auto-generated method stub
			return createItems(mult);
		}
	}
	public String registerGCM() {

		gcm = GoogleCloudMessaging.getInstance(this);
		regId = getRegistrationId(context);

		if (TextUtils.isEmpty(regId)) {

			registerInBackground();

			Log.d("RegisterActivity",
					"registerGCM - successfully registered with GCM server - regId: "
							+ regId);
		} else {
			Toast.makeText(getApplicationContext(),
					"RegId already available. RegId: " + regId,
					Toast.LENGTH_LONG).show();
		}
		return regId;
	}
    
	private String getRegistrationId(Context context) {
		SharedPreferences sp = getPreferences(MODE_PRIVATE);
		String registrationId = sp.getString(Utilities.REG_ID, "");
		if (TextUtils.isEmpty(registrationId)) {
			Log.i(TAG, "Registration not found.");
			return "";
		}
		int registeredVersion = sp.getInt(Utilities.APP_VERSION, Integer.MIN_VALUE);
		int currentVersion = getAppVersion(context);
		if (registeredVersion != currentVersion) {
			Log.i(TAG, "App version changed.");
			return "";
		}
		return registrationId;
	}

	private static int getAppVersion(Context context) {
		try {
			PackageInfo packageInfo = context.getPackageManager()
					.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			Log.d("RegisterActivity",
					"I never expected this! Going down, going down!" + e);
			throw new RuntimeException(e);
		}
	}

	private void registerInBackground() {
		new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... params) {
				String msg = "";
				try {
					if (gcm == null) {
						gcm = GoogleCloudMessaging.getInstance(context);
					}
					regId = gcm.register(Utilities.SENDER_ID);
					Log.d("RegisterActivity", "registerInBackground - regId: "
							+ regId);
					msg = "Device registered, registration ID=" + regId;

					storeRegistrationId(context, regId);
				} catch (IOException ex) {
					msg = "Error :" + ex.getMessage();
					Log.d("RegisterActivity", "Error: " + msg);
				}
				Log.d("RegisterActivity", "AsyncTask completed: " + msg);
				return msg;
			}

			@Override
			protected void onPostExecute(String msg) {
				Toast.makeText(getApplicationContext(),
						"Registered with GCM Server." + msg, Toast.LENGTH_LONG)
						.show();
			}
		}.execute(null, null, null);
	}

	private void storeRegistrationId(Context context, String regId) {
		int appVersion = getAppVersion(context);
		Log.i(TAG, "Saving regId on app version " + appVersion);
        SharedPreferences.Editor spe = getPreferences(MODE_PRIVATE).edit();
        spe.putString(Utilities.REG_ID, regId);
        spe.putInt(Utilities.APP_VERSION, appVersion);
        spe.commit();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private List<Product> createItems(int mult) {
		Log.d(TAG, "Lay 10 san pham dau tien choi cho vui thoi");
		List<Product> productList = new ArrayList<Product>();
        try {
        	HttpRequest req = new HttpRequest();
        	String a = req.makeServiceCall(Utilities.APP_SERVER_URL_GET_ALL_PRODUCT,HttpRequest.GET);;
        	Log.d(TAG,a);
        	try {
				JSONObject jsonObj = new JSONObject(a);
				JSONArray contacts = jsonObj.getJSONArray("productList");
				for (int ii = 0; ii < contacts.length(); ii++) {
					JSONObject c = contacts.getJSONObject(ii);
					int pServerId = Integer.parseInt(c.getString("pId"));
					int pCategory = Integer.parseInt(c.getString("pCategory"));
					int pColor = Integer.parseInt(c.getString("pColor"));
					String pName = c.getString("pName");
					float pPrice = Float.parseFloat(c.getString("pPrice"));
					float pSize = Float.parseFloat(c.getString("pSize"));
					String pDescription = c.getString("pDescription");
					String pImages = c.getString("pImages");
					String pOtherInfo = c.getString("pOtherInfo");
					String pTimeCreate = c.getString("pTimeCreate");
					int pUserId = Integer.parseInt(c.getString("pUserId"));
					
					Product p = new Product(
							pCategory,
							pColor,
							pName,
							pSize,
							pPrice,
							pDescription,
							pImages,
							pOtherInfo,
							pTimeCreate,
							pServerId,
							pUserId
							);
					productList.add(p);
					
				}
				return productList;
			} catch (Exception e) {
				// JSONException
				// TODO Auto-generated catch block
				e.printStackTrace();
			};
			
        } catch (Exception ex) {
        	ex.printStackTrace();
        }
		return productList;
	}
}
